/**
 * 安卓适配器组件
 * 检测安卓环境并应用相应的样式和行为适配
 */

import { useEffect, useState } from 'react';
import './AndroidAdapter.css';

class AndroidAdapter {
  constructor() {
    this.isAndroid = false;
    this.isAndroidWebView = false;
    this.androidVersion = null;
    this.deviceInfo = {};
    this.adaptationApplied = false;
    
    this.init();
  }

  init() {
    this.detectAndroid();
    this.getDeviceInfo();
    this.applyAdaptations();
  }

  /**
   * 检测是否为安卓设备
   */
  detectAndroid() {
    const userAgent = navigator.userAgent.toLowerCase();
    
    // 检测安卓系统
    this.isAndroid = /android/.test(userAgent);
    
    // 检测安卓WebView
    this.isAndroidWebView = this.isAndroid && (
      /wv/.test(userAgent) || // WebView标识
      /version\/[\d.]+.*chrome\/[\d.]+.*mobile safari/.test(userAgent) || // Chrome WebView
      window.Android !== undefined || // 原生Android接口
      document.documentElement.classList.contains('android-webview')
    );
    
    // 提取安卓版本
    const androidMatch = userAgent.match(/android\s([\d.]+)/);
    if (androidMatch) {
      this.androidVersion = parseFloat(androidMatch[1]);
    }
  }

  /**
   * 获取设备信息
   */
  getDeviceInfo() {
    this.deviceInfo = {
      userAgent: navigator.userAgent,
      screenWidth: window.screen.width,
      screenHeight: window.screen.height,
      windowWidth: window.innerWidth,
      windowHeight: window.innerHeight,
      devicePixelRatio: window.devicePixelRatio || 1,
      orientation: window.orientation || 0,
      isPortrait: window.innerHeight > window.innerWidth,
      isLandscape: window.innerWidth > window.innerHeight
    };
  }

  /**
   * 应用安卓适配
   */
  applyAdaptations() {
    if (!this.isAndroid || this.adaptationApplied) {
      return;
    }

    const body = document.body;
    const html = document.documentElement;

    // 添加安卓相关的CSS类
    html.classList.add('android-device');
    body.classList.add('android-webview');
    
    if (this.isAndroidWebView) {
      html.classList.add('android-webview-env');
      body.classList.add('android-webview-fix');
    }

    // 添加版本相关的类
    if (this.androidVersion) {
      html.classList.add(`android-${Math.floor(this.androidVersion)}`);
      
      // 针对不同版本的特殊处理
      if (this.androidVersion >= 10) {
        html.classList.add('android-modern');
      } else if (this.androidVersion >= 7) {
        html.classList.add('android-legacy');
      } else {
        html.classList.add('android-old');
      }
    }

    // 应用设备密度相关的类
    const dpr = this.deviceInfo.devicePixelRatio;
    if (dpr >= 3) {
      html.classList.add('android-xxxhdpi');
    } else if (dpr >= 2) {
      html.classList.add('android-xxhdpi');
    } else if (dpr >= 1.5) {
      html.classList.add('android-xhdpi');
    } else {
      html.classList.add('android-hdpi');
    }

    // 应用屏幕尺寸相关的类
    if (this.deviceInfo.windowWidth <= 480) {
      html.classList.add('android-small');
    } else if (this.deviceInfo.windowWidth <= 768) {
      html.classList.add('android-medium');
    } else {
      html.classList.add('android-large');
    }

    // 设置CSS自定义属性
    this.setCSSCustomProperties();

    // 修复安卓WebView的一些问题
    this.fixAndroidWebViewIssues();

    // 监听方向变化
    this.setupOrientationListener();

    // 监听键盘显示/隐藏
    this.setupKeyboardListener();

    this.adaptationApplied = true;
  }

  /**
   * 设置CSS自定义属性
   */
  setCSSCustomProperties() {
    const root = document.documentElement;
    
    // 设备信息
    root.style.setProperty('--android-screen-width', `${this.deviceInfo.screenWidth}px`);
    root.style.setProperty('--android-screen-height', `${this.deviceInfo.screenHeight}px`);
    root.style.setProperty('--android-window-width', `${this.deviceInfo.windowWidth}px`);
    root.style.setProperty('--android-window-height', `${this.deviceInfo.windowHeight}px`);
    root.style.setProperty('--android-device-pixel-ratio', this.deviceInfo.devicePixelRatio);
    
    // 状态栏高度估算
    const statusBarHeight = this.estimateStatusBarHeight();
    root.style.setProperty('--android-status-bar-height', `${statusBarHeight}px`);
    
    // 导航栏高度估算
    const navigationBarHeight = this.estimateNavigationBarHeight();
    root.style.setProperty('--android-navigation-bar-height', `${navigationBarHeight}px`);
  }

  /**
   * 估算状态栏高度
   */
  estimateStatusBarHeight() {
    const dpr = this.deviceInfo.devicePixelRatio;
    
    // 根据设备密度估算状态栏高度
    if (dpr >= 3) {
      return 72; // xxxhdpi
    } else if (dpr >= 2) {
      return 48; // xxhdpi
    } else if (dpr >= 1.5) {
      return 36; // xhdpi
    } else {
      return 24; // hdpi
    }
  }

  /**
   * 估算导航栏高度
   */
  estimateNavigationBarHeight() {
    const dpr = this.deviceInfo.devicePixelRatio;
    const hasNavigationBar = this.deviceInfo.screenHeight > this.deviceInfo.windowHeight + this.estimateStatusBarHeight();
    
    if (!hasNavigationBar) {
      return 0;
    }
    
    // 根据设备密度估算导航栏高度
    if (dpr >= 3) {
      return 144; // xxxhdpi
    } else if (dpr >= 2) {
      return 96; // xxhdpi
    } else if (dpr >= 1.5) {
      return 72; // xhdpi
    } else {
      return 48; // hdpi
    }
  }

  /**
   * 修复安卓WebView的问题
   */
  fixAndroidWebViewIssues() {
    // 修复输入框缩放问题
    this.fixInputZoomIssue();
    
    // 修复滚动问题
    this.fixScrollIssues();
    
    // 修复触摸反馈问题
    this.fixTouchFeedback();
    
    // 修复字体渲染问题
    this.fixFontRendering();
  }

  /**
   * 修复输入框缩放问题
   */
  fixInputZoomIssue() {
    // 防止输入框聚焦时页面缩放
    const inputs = document.querySelectorAll('input, textarea, select');
    inputs.forEach(input => {
      input.classList.add('android-input-fix');
    });
    
    // 监听新添加的输入框
    const observer = new MutationObserver((mutations) => {
      mutations.forEach((mutation) => {
        mutation.addedNodes.forEach((node) => {
          if (node.nodeType === 1) {
            const newInputs = node.querySelectorAll('input, textarea, select');
            newInputs.forEach(input => {
              input.classList.add('android-input-fix');
            });
          }
        });
      });
    });
    
    observer.observe(document.body, { childList: true, subtree: true });
  }

  /**
   * 修复滚动问题
   */
  fixScrollIssues() {
    // 为滚动容器添加优化类
    const scrollContainers = document.querySelectorAll('.ant-layout-content, .ant-table-body, .ant-modal-body');
    scrollContainers.forEach(container => {
      container.classList.add('android-scroll-container');
    });
  }

  /**
   * 修复触摸反馈问题
   */
  fixTouchFeedback() {
    // 为可点击元素添加触摸反馈优化
    const clickableElements = document.querySelectorAll('button, .ant-btn, .ant-menu-item, .ant-table-row');
    clickableElements.forEach(element => {
      element.classList.add('android-touch-feedback');
    });
  }

  /**
   * 修复字体渲染问题
   */
  fixFontRendering() {
    document.body.classList.add('android-text-rendering');
  }

  /**
   * 设置方向变化监听
   */
  setupOrientationListener() {
    const handleOrientationChange = () => {
      setTimeout(() => {
        this.getDeviceInfo();
        this.setCSSCustomProperties();
        
        // 重新应用方向相关的类
        const html = document.documentElement;
        html.classList.remove('android-portrait', 'android-landscape');
        
        if (this.deviceInfo.isPortrait) {
          html.classList.add('android-portrait');
        } else {
          html.classList.add('android-landscape');
        }
      }, 100);
    };
    
    window.addEventListener('orientationchange', handleOrientationChange);
    window.addEventListener('resize', handleOrientationChange);
  }

  /**
   * 设置键盘显示/隐藏监听
   */
  setupKeyboardListener() {
    let initialViewportHeight = window.innerHeight;
    
    const handleResize = () => {
      const currentHeight = window.innerHeight;
      const heightDifference = initialViewportHeight - currentHeight;
      
      // 如果高度减少超过150px，认为是键盘显示
      if (heightDifference > 150) {
        document.documentElement.classList.add('android-keyboard-visible');
        document.documentElement.style.setProperty('--android-keyboard-height', `${heightDifference}px`);
      } else {
        document.documentElement.classList.remove('android-keyboard-visible');
        document.documentElement.style.setProperty('--android-keyboard-height', '0px');
      }
    };
    
    window.addEventListener('resize', handleResize);
  }

  /**
   * 获取适配信息
   */
  getAdaptationInfo() {
    return {
      isAndroid: this.isAndroid,
      isAndroidWebView: this.isAndroidWebView,
      androidVersion: this.androidVersion,
      deviceInfo: this.deviceInfo,
      adaptationApplied: this.adaptationApplied
    };
  }
}

// 创建全局实例
const androidAdapter = new AndroidAdapter();

// React Hook
export const useAndroidAdapter = () => {
  const [adaptationInfo, setAdaptationInfo] = useState(androidAdapter.getAdaptationInfo());
  
  useEffect(() => {
    // 监听适配状态变化
    const updateAdaptationInfo = () => {
      setAdaptationInfo(androidAdapter.getAdaptationInfo());
    };
    
    // 初始更新
    updateAdaptationInfo();
    
    // 监听窗口变化
    window.addEventListener('resize', updateAdaptationInfo);
    window.addEventListener('orientationchange', updateAdaptationInfo);
    
    return () => {
      window.removeEventListener('resize', updateAdaptationInfo);
      window.removeEventListener('orientationchange', updateAdaptationInfo);
    };
  }, []);
  
  return adaptationInfo;
};

export default androidAdapter;